<?php
namespace App\Http\Controllers\Wap;

use App\Http\Controllers\Controller;
use App\Models\Goods;
use App\Models\GoodsBuys;
use App\Models\GoodsEvaluate;
use App\Models\Location;
use App\Models\Member;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Services\ChuangLan\ChuanglanSmsApi;
use Illuminate\Support\Facades\Log;

/**
 * 推广
 *
 * @author Miluo Huang
 */
class SpreadController extends Controller
{
    public function __construct(Request $request)
    {
        if ($request->has('source')) {
            $channel = get_reserve_source($request->input('source'));
            \Session::put('channel', $channel);
        }

//        if($request->has('qz_gdt')){
//            Log::debug('qz_gdt:'.$request->input('qz_gdt'));
//            \Session::put('qz_gdt', $request->input('qz_gdt'));
//        }
//
//        if($request->has('gdt_vid')){
//            Log::debug('gdt_vid:'.$request->input('gdt_vid'));
//            \Session::put('qz_gdt', $request->input('gdt_vid'));
//        }

//        if(!env('APP_DEBUG')) {
//            $access_token = $this->getAccessToken();
//            if ($access_token === false) {
//                $authorization_code = $this->getAuthorizationCode();
//                if ($authorization_code === false) {
//                    if (!$request->has('authorization_code')) {
//                        $url = 'https://developers.e.qq.com/oauth/authorize?client_id=1106383180&redirect_uri=' . urlencode($request->getUri());
//                        Cache::put('getUri', urlencode($request->getUri()), 5);
//                        //301跳转m端
//                        header('HTTP/1.1 302 Moved Permanently');
//                        header('Location: ' . $url);
//                        die;
//                    } else {
//                        $authorization_code = $request->input('authorization_code');
//                        $url = 'https://api.e.qq.com/oauth/token?client_id=1106383180&client_secret=83ab8e1c099ea04200536d09da77ac18&grant_type=authorization_code&authorization_code=' . $authorization_code . '&redirect_uri=' . Cache::get('getUri');
//                        Log::debug('authorization_code:' . $authorization_code);
//                        Log::debug('url:' . $url);
//                        $data = httpGet($url);
//                        Log::debug('access_token:' . json_encode($data));
//                        $data = json_decode($data);
//                        $access_token = $data->data->access_token;
//                        $refresh_token = $data->data->refresh_token;
//                        $this->setAccessToken($access_token);
//                        $this->setRefreshToken($refresh_token);
//                    }
//
//                }
//            }
//        }

    }

    /**
     * 推广
     */
    public function getGoodDetail(Request $request)
    {
//        if($request->input('id') == 196){
//            return redirect()->to(route('WapSpreadHome'));
//        }
        //取得省市区数据
        if (Cache::has('wap_p_location') && Cache::get('wap_p_location')) {
            $province = Cache::get('wap_p_location');
        } else {
        $province = Location::where('pid', 0)->get();
            Cache::put('wap_p_location', $province, 200);
        }
        //取的商品数据
        if (Cache::has('wap_goods_info_' . $request->input('id'))) {
            $data = Cache::get('wap_goods_info_' . $request->input('id'));
        } else {
        $data = Goods::find($request->input('id'));
            Cache::put('wap_goods_info_' . $request->input('id'), $data, 15);
        }

        $attributes = [];
        foreach ($data->goods_attribute as $key => $item) {
            $attributes[] = explode('#', $item->value);
        }
        //获取产品
        $goods = Goods::where('status', 1)->orderBy('sort_at', 'desc')->where('status', 1)->where('is_item', 0)->get();
        //产品评价
        $eva = GoodsEvaluate::where('evaluate_at','>=',Carbon::now()->subWeek(1))->orderByRaw('rand() desc')->limit(30)->get();

        //购买记录
        $buys = GoodsBuys::where('created_at','>=',Carbon::now()->subWeek(1))->orderByRaw('rand() desc')->limit(30)->get();

        // 替换图片
        $a = $data->details;
        $pregRule =  "/<[img|IMG].*?src=[\'|\"](.*?)[\'|\"].*?[\/]?>/";
        $content = preg_replace($pregRule, '<img src="" style="max-width:100%" class="lazy" data-original="${1}'.'">', $a);
        $data->details = $content;

        $cache_key = 'marking';
        if(Cache::has($cache_key)) {
            $data_model = Cache::get($cache_key);
        }else{
            $data_model = [
                'urls' => '',
                'model' => []
            ];
        }
        $url = explode(',',$data_model['urls']);

        return view('wap.spread.good')->withProvince($province)
            ->withData($data)->withAttributes($attributes)
            ->withGet($request->all())->withGoods($goods)
            ->withEva($eva)->withHost($request->getHttpHost())
            ->withRand(rand(0, 99))->withBuys($buys)->withUrl($url)->withModel($data_model['model']);
    }

    /**
     * 下单
     */
    public function orderSave(Request $request)
    {
        // 验证输入。
        $this->validate($request, [
            'size'        => 'required',
            'color'       => 'required',
            'number'      => 'required',
            'real_name'   => 'required',
            'mobile'      => [
                'required',
                'mobile'
            ],
            'province_id' => 'required',
            'address'     => 'required',
            'goods_id'    => 'required',
            'city_id'     => 'required',
            'area_id' => 'required'
        ], [
            'size.required'        => '请选择尺码',
            'color.required'       => '请选择颜色',
            'number.required'      => '请选择数量',
            'real_name.required'   => '请填写姓名',
            'mobile.required'      => '请填写手机号',
            'mobile.mobile'        => '请填写正确手机号',
            'province_id.required' => '请选择所在省份',
            'address.required'     => '请填写详细地址',
            'goods_id.required'    => '请选择商品',
            'city_id.required'     => '请选择城市',
            'area_id.required' => '请选择县市/地区'
        ]);

        $member = Member::where('mobile', $request->input('mobile'))->first();
        if (is_null($member)) {
            $member           = new Member();
            $member->mobile   = $request->input('mobile');
            $member->nickname = $request->input('real_name');
            $member->save();
        }

        $count = Order::where('created_at', '>=', date('Y-m-d H:i:s', strtotime('-5 minute')))->where('member_id', $member->id)->count('id');
        if ($count >= 3) {
            return response()->json([
                'status'  => 1,
                'message' => '购买太频繁,请稍后再试'
            ]);
        }

        $order = new Order();
        $order->member()->associate($member);
        $order->address     = $request->input('address');
        $order->province_id = $request->input('province_id');
        $order->real_name   = $request->input('real_name');
        $request->has('city_id') ? $order->city_id = $request->input('city_id') : '';
        $request->input('area_id') ? $order->area_id = $request->input('area_id') : '';
        $request->input('leave_word') ? $order->leave_word = $request->input('leave_word') : '';
        $request->input('goods_id') ? $order->goods_id = $request->input('goods_id') : '';
        $order->pay_mode = 1;
        $order->city_id  = $request->input('city_id');
        $order->area_id  = $request->input('area_id');
        $order->price    = $request->input('money');
        if (\Session::has('channel')) {
            $order->channel()->associate(\Session::get('channel'));
        }
        $order->info = json_encode([
            '货品名' => $request->input('goods_name'),
            '尺码'  => $request->input('size'),
            '颜色'  => $request->input('color'),
            '数量'  => $request->input('number')
        ]);
        $order->save();
        $order->goods()->attach($request->input('goods_id'));

        //发送短信
        $sms        = new ChuanglanSmsApi();
        $sms->sendSMS($request->input('mobile'), $request->input('real_name').'女士您已成功订购'.$request->input('number').'双' . $request->input('color') .$request->input('size').'码鞋子，我们将尽快为您安排发货，请耐心等待。');

//        if(\Session::has('qz_gdt')){
//            $url = 'https://api.e.qq.com/v1.0/user_actions/add?access_token='.$this->getAccessToken().'&timestamp='.time().'&nonce='.time().rand(0,9999);
//            $data = [
//                'account_id' => '5461205',
//                'actions' => [
//                    [
//                        "user_action_set_id"=>"1106309349",
//                        "url"=> route('WapSpreadGood',['id'=>$request->input('goods_id')]),//"http://mainx.tmall.lindaying.com/wap/spread/goods?id=142",
//                        "action_time"=> time(),
//                        "action_type" =>  "COMPLETE_ORDER",
//                        "trace"=>[
//                            "click_id"=> \Session::get('qz_gdt')
//                        ],
//                        "value"=> $request->input('money')*100
//                    ]
//                ]
//            ];
//            $r = _curl_request($url,json_encode($data));
//            Log::debug('place_order:'.json_encode($r).'|order:'.$order->id);
//        }

        return response()->json([
            'status'  => 1,
            'order_id' => $order->id,
            'message' => '提交成功'
        ]);
    }

    /**
     * 首页
     */
    public function getHome(Request $request){
        $data = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',1)->get();
        $data2 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',2)->get();
        $data3 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',3)->get();
        $data4 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',4)->get();
        $data5 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',5)->get();
        $data7 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',7)->get();
        $top = Goods::where('top_recommended',1)->first();
        return view('wap.spread.index')->withData($data)->withHost($request->getHttpHost())->withTop($top)->withData2($data2)->withData3($data3)->withData4($data4)->withData5($data5)->withData7($data7);
    }

    /**
     * 订购成功
     */
    public function getResult(Request $request){
        $data = Order::find($request->input('order_id'));
        return view('wap.spread.result')->withData($data);
    }

    public function getHome2(Request $request){
        $data_long = Goods::where('is_index',1)->orderBy('index_sort_at','desc')->where('is_long',1)->get();
        $data = Goods::where('is_index',1)->orderBy('index_sort_at','desc')->where('is_long',0)->get();
        return view('wap.spread.index2')->withData($data)->withLongData($data_long)->withHost($request->getHttpHost());
    }

    public function getHome3(Request $request){
//        $url = 'https://api.e.qq.com/v1.0/user_action_sets/get?nonce='.time().'&access_token=86144e67b69279539f3043080c2a370e&timestamp='.time().'&account_id=5461205';
//        $r = httpGet($url);//dd($r);
//        $url = 'https://api.e.qq.com/v1.0/user_action_sets/add?access_token=86144e67b69279539f3043080c2a370e&timestamp='.time().'&nonce=1';
//        $data = [
//            'account_id' => '5461205',
//            "type" => "WEB",
//            "name" => "提交订单",
//            "description" => "提交订单"
//        ];
////        $r = _curl_request($url,json_encode($data));
////        dd($r);
//        $url = 'https://api.e.qq.com/v1.0/user_actions/add?access_token=86144e67b69279539f3043080c2a370e&timestamp='.time().'&nonce='.time().rand(0,9999);
//        $data = [
//            'account_id' => '5461205',
//            'actions' => [
//                    [
//                    "user_action_set_id"=>"1106309349",
//                    "url"=> "http://mainx.tmall.lindaying.com/wap/spread/goods?id=142",
//                    "action_time"=> time(),
//                    "action_type" =>  "COMPLETE_ORDER",
//                    "trace"=>[
//                        "click_id"=> "1"
//                    ],
//                    "value"=> 10000
//                ]
//            ]
//        ];
//        $r = _curl_request($url,json_encode($data));
//        dd($r);
        $data = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',1)->get();
        $data2 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',2)->get();
        $data3 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',3)->get();
        $data4 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',4)->get();
        $data5 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',5)->get();
        $data7 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',7)->get();
        $data8 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',8)->get();
        $data6 = Goods::where('is_index',1)->orderBy('sort_at','desc')->where('show_place',6)->get();
        $top = Goods::where('top_recommended',1)->get();
        $view = 'wap.spread.indexcat2';
        if(!is_mobile_request()){
            $view = 'wap.spread.indexcatpc';
        }
        return view($view)->withData($data)
            ->withHost($request->getHttpHost())
            ->withTop($top)->withData2($data2)
            ->withData3($data3)
            ->withData4($data4)
            ->withData5($data5)
            ->withData7($data7)
            ->withData6($data6)
            ->withData8($data8);
    }


    private function getAccessToken(){
        $cache_key = 'access_token';
        if(!Cache::has($cache_key)){
            if($this->getRefreshToken() !== false){
                $url = 'https://api.e.qq.com/oauth/token?client_id=1106383180&client_secret=83ab8e1c099ea04200536d09da77ac18&grant_type=refresh_token&refresh_token='.$this->getRefreshToken();
                $data = httpGet($url);
                Log::debug('refresh_token:'.json_encode($data));
                if($data !== false){
                    $data = json_decode($data);
                    $access_token = $data->data->access_token;
                    $this->setAccessToken($access_token);
                    return $access_token;
                }else{
                    return false;
                }
            }else{
                return false;
            }
        }
        $access_token = Cache::get($cache_key);

        return $access_token;
    }

    private function getRefreshToken(){
        $cache_key = 'refresh_token';
        if(!Cache::has($cache_key)) {
            return false;
        }
        $refresh_token = Cache::get($cache_key);
        return $refresh_token;
    }

    private function setAccessToken($access_token){
        $cache_key = 'access_token';

        Cache::put($cache_key,$access_token,60*24-1);

        return true;
    }

    private function setRefreshToken($refresh_token){
        $cache_key = 'refresh_token';

        Cache::put($cache_key,$refresh_token,60*24*30-1);

        return true;
    }

    private function getAuthorizationCode(){
        $cache_key = 'authorization_code';
        if(!Cache::has($cache_key)){
            return false;
        }

        return Cache::get($cache_key);
    }

    private function setAuthorizationCode($authorization_code){
        $cache_key = 'authorization_code';

        Cache::put($cache_key,$authorization_code,4);

        return  true;
    }

    private function setUserAction($account_id,$type='WEB'){
        $url = 'https://api.e.qq.com/v1.0/user_action_sets/add';
    }




}
